День 4 Летней школы Julia
Автор
Поиск минимума
In [ ]:
gr()
Out[0]:
In [ ]:
f_r( x, y ) = @. (1.0 - x)^2 + 100.0 * (y - x^2)^2
x_r = -1:0.05:1
y_r = -1:0.05:1
contour( x_r, y_r, f_r.(x_r', y_r ), levels=30, cmap=:viridis, cbar=false )
Out[0]:
In [ ]:
]add Optim
In [ ]:
using Optim
In [ ]:
f(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
Out[0]:
In [ ]:
x0 = [0.0, 0.0]
res = optimize( f, x0 )
Out[0]:
In [ ]:
res.minimizer
Out[0]:
In [ ]:
res.minimum
Out[0]:
In [ ]:
?res
Out[0]:
In [ ]:
res = optimize( f, x0, store_trace = true )
Out[0]:
In [ ]:
?res
Out[0]:
In [ ]:
dump( res.trace )
In [ ]:
ite = getfield.( res.trace, :iteration )
val = getfield.( res.trace, :value )
plot( ite, val )
Out[0]:
In [ ]:
res = optimize( f, x0, store_trace = true, extended_trace=true )
Out[0]:
In [ ]:
xs = first.( Optim.centroid_trace(res) );
ys = last.( Optim.centroid_trace(res) );
f_r( x, y ) = @. (1.0 - x)^2 + 100.0 * (y - x^2)^2
x_r = -0.5:0.05:1.5
y_r = -0.5:0.05:1.5
contour( x_r, y_r, f_r.(x_r', y_r ), levels=30, cmap=:viridis, cbar=false )
plot!( xs, ys, lw=4, label="Nelder-Mead" )
Out[0]:
In [ ]:
x0 = [0.0, 0.0]
res1 = optimize(f, x0, GradientDescent(), Optim.Options(store_trace=true, extended_trace=true) );
res2 = optimize(f, x0, MomentumGradientDescent(), Optim.Options(store_trace=true, extended_trace=true) );
res3 = optimize(f, x0, LBFGS(), Optim.Options(store_trace=true, extended_trace=true) );
res4 = optimize(f, x0, ConjugateGradient(), Optim.Options(store_trace=true, extended_trace=true) );
In [ ]:
plot( first.( Optim.x_trace(res1) ), last.( Optim.x_trace(res1) ), lw=2, ls=:dash, c=5, label="GradientDescent" )
plot!( first.( Optim.x_trace(res2) ), last.( Optim.x_trace(res2) ), lw=2, ls=:dash, c=6, label="MomentumGradientDescent" )
plot!( first.( Optim.x_trace(res3) ), last.( Optim.x_trace(res3) ), lw=2, ls=:dash, c=7, label="LBFGS" )
plot!( first.( Optim.x_trace(res4) ), last.( Optim.x_trace(res4) ), lw=2, ls=:dash, c=8, label="ConjugateGradient" )
Out[0]:
In [ ]:
plot(
plot( last.( Optim.centroid_trace(res) ), first.( Optim.centroid_trace(res) ), c=5, title="Nelder-Mead", markershape=:circle ),
plot( last.( Optim.x_trace(res1) ), first.( Optim.x_trace(res1) ), c=6, title="GradientDescent", markershape=:circle ),
plot( last.( Optim.x_trace(res2) ), first.( Optim.x_trace(res2) ), c=7, title="MomentumGradientDescent", markershape=:circle ),
plot( last.( Optim.x_trace(res3) ), first.( Optim.x_trace(res3) ), c=8, title="LBFGS", markershape=:circle ),
plot( last.( Optim.x_trace(res4) ), first.( Optim.x_trace(res4) ), c=9, title="ConjugateGradient", markershape=:circle ),
leg=false, titlefont=font(8)
)
Out[0]:
In [ ]:
Создаем полиномы
In [ ]:
]add Polynomials
In [ ]:
using Polynomials
In [ ]:
]add CSV
In [ ]:
using CSV, DataFrames
data_df = CSV.read("Filip.csv", header=true, delim=' ', ignorerepeated=true, DataFrame );
coeffs_df = CSV.read("Filip_coeffs.csv", header=true, delim=' ', ignorerepeated=true, DataFrame );
In [ ]:
extrema(data_df.x)
Out[0]:
In [ ]:
scatter( data_df.x, data_df.y, label="Данные" )
plot!( Polynomial(coeffs_df.Estimate), lw=3, label="Полином" )
plot!( xlimits=extrema(data_df.x), ylimits=extrema(data_df.y) )
Out[0]:
In [ ]:
p = Polynomials.fit( data_df.x, data_df.y, 10 )
Out[0]:
In [ ]:
plot!( p, lw=3, label="Оценка полинома" )
plot!( xlimits=extrema(data_df.x), ylimits=extrema(data_df.y) )
Out[0]:
In [ ]:
]add GLM
In [ ]:
using GLM
p_lm = lm( @formula( y ~ sin(x) + x^2), data_df )
Out[0]:
In [ ]:
scatter!( data_df.x, GLM.predict( p_lm, data_df ), lw=3, label="GLM" )
plot!( xlimits=extrema(data_df.x), ylimits=extrema(data_df.y))
Out[0]:
In [ ]:
Обучим нейросеть
In [ ]:
]add Flux
In [ ]:
using Flux
In [ ]:
Xs = Float32.( 0:0.1:10 )
Ys = Float32.( 2Xs .+ 2(rand(length(Xs)).-0.5) )
plot( Xs, Ys )
Out[0]:
In [ ]:
model = Dense( 1 => 1 )
Out[0]:
In [ ]:
loss(x,y) = Flux.mse(model(x), y)
Out[0]:
In [ ]:
opt = Flux.Adam(0.1)
Out[0]:
In [ ]:
data = [(Xs', Ys')]
Out[0]:
In [ ]:
model( [1] )
Out[0]:
In [ ]:
for i in 1:1000
Flux.train!( loss, Flux.params(model), data, opt )
end
In [ ]:
X_прогноз = [ [x] for x in Xs ]
Y_прогноз = model.( X_прогноз )
plot( Xs, Ys, label="Исходная выборка", legend=:topleft, lw=2 )
plot!( Xs, vec(hcat(Y_прогноз...)), label="Прогноз", lw=2 )
Out[0]:
In [ ]:
model.weight
Out[0]:
In [ ]:
model.bias
Out[0]:
In [ ]:
using Symbolics
@variables x1
model( [x1] )
Out[0]:
Многослойная нейросеть
In [ ]:
model = Chain( Dense(1=>4, relu), Dense(4=>2, sigmoid), Dense(2=>1) )
Out[0]:
In [ ]:
@variables x1
model( [x1] )
Out[0]:
In [ ]:
#]add ChainPlots
In [ ]:
#using ChainPlots
In [ ]:
#gr()
#plot( model )
Классификатор
In [ ]:
model = Dense( 1=>2 )
Out[0]:
In [ ]:
loss(x,y) = Flux.crossentropy( model(x), y )
Out[0]:
In [ ]:
?Flux.crossentropy
Out[0]:
Вычисления на GPU
In [ ]:
using CUDA
In [ ]:
# CUDA.set_runtime_version!(v"12.2")
In [ ]:
@time CUDA.rand( 10000,10000 ).^2;
In [ ]:
@time CUDA.rand( 10000,10000 ).^2;
In [ ]:
@time rand( 10000,10000 ).^2;
In [ ]:
@time rand( 10000,10000 ).^2;
In [ ]:
CUDA.functional()
Задачи для изучения синтаксиса
Найти минимум функции f(x) = (x - 3)^2 + 5 с помощью градиентного спуска.
In [ ]:
using Optim
f(x) = (x[1] - 3)^2 + 5 # x передается как массив, даже если он из одного элемента
result = optimize(f, [0.0]) # Начинаем поиск с x = 0
println("Минимум найден в x = ", result.minimizer[1], " значение f = ", result.minimum)
Обучить однонейронную сеть (линейную регрессию) предсказывать y = 2x + 1.
In [ ]:
using Flux, Statistics
# 1. Создаем данные: y = 2x + 1 + небольшой шум
x = rand(100) * 10
y = 2 .* x .+ 1 .+ randn(100)
# 2. Создаем модель: один полносвязный слой без активации (линейная регрессия)
model = Dense(1 => 1)
# 3. Функция потерь
loss(x, y) = Flux.mse(model(x), y)
# 4. Данные и оптимизатор
data = [(x[i],y[i]) for i in 1:100]
opt = Descent(0.01) # Gradient descent with learning rate 0.01
# 5. Цикл обучения
for epoch in 1:100
Flux.train!(loss, Flux.params(model), data, opt)
end
# Смотрим, чему равны оценки веса и смещени
println("Веса: ", model.weight)
println("Смещение: ", model.bias)
# Должны быть близки к 2 и 1









